package xyz.wpxy.iotlink.network.mqtt.config;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import xyz.wpxy.iotlink.network.mqtt.server.service.MqttBrokerConsume;


@Component
@ConditionalOnBean(MqttBrokerConfig.class)
public class MqttBrokerProvider {
    private final Logger logger = LoggerFactory.getLogger(MqttBrokerProvider.class);

    @Autowired(required = false)
    private MqttBrokerConfig config;

    @Autowired
    private MqttBrokerConsume mqttBrokerConsume;

    public void create() {
        create(config, config.getTopics());
    }

    /**
     * 创建网络组件-mqtt-broker
     */
    public void create(MqttBrokerConfig config, String[] topics) {
        try {
            MqttClient mqttClient = new MqttClient(config.getUrl(), config.getClientId(), new MemoryPersistence());
            mqttBrokerConsume.setClient(mqttClient, topics);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(config.getUsername());
            options.setPassword(config.getPassword().toCharArray());
            //再次连接时是否清除上次的session，即重新连接时是否不接收未收到的消息。只有重新连接时才能够更改此参数
            options.setCleanSession(config.isCleanSession());
            options.setAutomaticReconnect(config.isAutomaticReconnect());
            options.setConnectionTimeout(config.getConnectionTimeout());
            options.setKeepAliveInterval(config.getKeepAliveInterval());

            mqttClient.connect(options);
            mqttClient.setCallback(mqttBrokerConsume);
            if (topics != null && topics.length > 0) {
                mqttClient.subscribe(topics);
            }
        } catch (Exception e) {
            logger.error("网络组件-mqtt-border创建失败", e);
        }
    }
}
